const CACHE_PREFIX = 'cache_';
const IMAGE_CACHE_TIME = 24 * 60 * 60 * 1000; // 24小时

const cache = {
  // 设置缓存
  set: function(key, value, expire = IMAGE_CACHE_TIME) {
    const data = {
      value,
      expire: Date.now() + expire
    };
    wx.setStorageSync(CACHE_PREFIX + key, JSON.stringify(data));
  },

  // 获取缓存
  get: function(key) {
    const data = wx.getStorageSync(CACHE_PREFIX + key);
    if (!data) return null;
    
    try {
      const { value, expire } = JSON.parse(data);
      if (Date.now() > expire) {
        wx.removeStorageSync(CACHE_PREFIX + key);
        return null;
      }
      return value;
    } catch (e) {
      return null;
    }
  },

  // 移除缓存
  remove: function(key) {
    wx.removeStorageSync(CACHE_PREFIX + key);
  },

  // 清理过期缓存
  clearExpired: function() {
    const keys = wx.getStorageInfoSync().keys;
    keys.forEach(key => {
      if (key.startsWith(CACHE_PREFIX)) {
        const data = wx.getStorageSync(key);
        try {
          const { expire } = JSON.parse(data);
          if (Date.now() > expire) {
            wx.removeStorageSync(key);
          }
        } catch (e) {
          wx.removeStorageSync(key);
        }
      }
    });
  }
};

module.exports = cache; 